<template>
	<view class="carbon-footprint">
		<view class="top">
			<view class="title">
				产品碳固存&nbsp;&nbsp;
			</view>
			<view class="switch">
				<view class="iconfont icon-xiangzuo fx" @click="upd(-1)"></view>
				<view class="iconfont icon-xiangyou fx" @click="upd(1)"></view>
			</view>
		</view>
		
		<view class="date" v-if="date">{{ date }}</view>
		
		<view class="range" >
			<view
				@click="dateUnit(item.index)" class="item"
				:class="{check: dateIndex==item.index}"
				v-for="(item, index) in dateArr" :key="index" >
				{{ item.name }}
			</view>
		</view>
		
		<NullData v-show="pieData.length==0"></NullData>
		
		<view v-show="pieData.length!=0" class="content">
			<view class="echarts-content">
				<view class="echarts">
					<uni-ec-canvas
						v-if="pieData.length > 0"
						class="uni-ec-canvas tt"  
						id="line-chart"  
						ref="canvas"  
						canvas-id="lazy-load-chart"  
						:ec="ec"  
					></uni-ec-canvas>
				</view>
				<view class="list-content">
					<view class="item" v-for="(item, index) in pieData" :key="index">
						<view class="card-item">
							<view>
								<view class="circle" :style="'background-color: '+(ec.option.color[index])+';'"></view>
								<!-- {{  }} -->
								<view class="name">
									{{ item.name }}
									<view>
										{{ item.value }}kgCO₂e
									</view>
								</view>
							</view>
							<view class="percent">{{ item.per }}%</view>
						</view>
					</view>
				</view> 				
			</view>
		</view>
	</view>
</template>

<script>
	import NullData from '@/common/NullData/NullData'
	import uniEcCanvas from '@/components/uni-ec-canvas/uni-ec-canvas.vue'
	import * as echarts from '@/components/uni-ec-canvas/echarts'
	
	import { getPieDay as getPieDayApi, getPieWeek as getPieWeekApi, getPieMonth as getPieMonthApi } from '@/api/info'
	
	export default {
		props: {
			allGoods: {
				type: Array,
				default: []
			}
		},
		data() {
			return {
				days: [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
				year: 0,
				month: 0,
				day: 0,
				dateArr: [{name: '日', index: 0}, {name: '周', index: 1}, {name: '月', index: 2}],
				dateIndex: 0,
				isEmpty: false,
				dataInfo: false,
				cid: 0,
				day: "2023-04-10",
				type: 1,
				date: '',
				pieData: [],
				sum: 0,
				maxY: 0,
				maxM: 0,
				ec: {
					lazyLoad: false,  
					option: {  
						tooltip: {
							trigger: 'item'
						},
						color: ['#25eaff', '#3ca170', '#f9c956', '#ef6567', '#91cd77', '#ea7ccc', '#fc8452', '#5470c6'],
						series: [
							{
								name: '碳中和：',
								type: 'pie',
								radius: '50%',
								data: [
									{ value: 1048, name: '去你的' },
									{ value: 735, name: 'Direct' },
									{ value: 580, name: 'Email' },
									{ value: 484, name: 'Union Ads' },
									{ value: 300, name: '艹' }
								],
								emphasis: {
									itemStyle: {
										shadowBlur: 10,
										shadowOffsetX: 0,
										shadowColor: 'rgba(0, 0, 0, 0.5)'
									}
								},
							}
						]
					}
				}  
				
			}
		},
		onReady () {
			
		    setTimeout(()=>{  
		        this.$refs['canvas'].init()  
				
		    }, 1000) // 两秒之后延迟加载  
		
		    setTimeout(()=>{  
				
		    },2000)  
		},
		components: {
			uniEcCanvas,
			NullData
		},
		created() {
			this.cid=this.$store.getters.getUser.cid
			this.date=this.currentTime(0)
			// console.log('date: ', this.date)
			// console.log('day: ', this.day)
			this.__getPie(this.date)
		},
		methods: {
			upd(val){
				if(this.dateIndex == 0) { // 日
					let temp = this.day + val;
					if (temp > this.days[this.month]) {
						if (this.month + 1 > 12) this.year ++, this.month = 1;
						else this.month ++;
						this.day = 1;
					} else this.day = temp;
					if (temp < 1){
						if (this.month === 1) this.year --, this.month = 12;
						else this.month --;
						this.day = this.days[this.month];
					} else this.day = temp;
					this.date = this.transDate(this.year, this.month, this.day);
					this.__getPie(this.transDate(this.year, this.month, this.day));
				}else if(this.dateIndex == 1) { // 周
					// console.log('begin:'+this.month+'---'+this.day);
					let temp = this.day + val * 7;  // 加一周
					if (temp > this.days[this.month]) {  // 大于当前月的天数
						this.day = temp - this.days[this.month];  // 先更新日
						if (this.month + 1 > 12) this.year ++, this.month = 1;
						else this.month ++;
					} else if (temp < 1){  // 小于当前月的天数
						if (this.month === 1) this.year --, this.month = 12;
						else this.month --;
						this.day = this.days[this.month] - (-temp);
					} else this.day = temp;
					// console.log('after:'+this.month+'---'+this.day);
					this.date = this.transDate(this.year, this.month, this.day);	
					var last = new Date(this.year, this.month - 1, this.day);
					var monday = this.getMonday(new Date(last.getTime()));
					var sunday = this.getSunday(new Date(last.getTime()));
					this.date = monday + ' ~ ' + sunday;

					this.__getPie(this.transDate(this.year, this.month, this.day));
				}else if(this.dateIndex == 2){ // 月
					let _month = (new Date()).getMonth() + 1;
					let _year = (new Date()).getFullYear();
					console.log(_month, _year, '---');
					let mon = this.month + val;
					let yea = this.year;
					
					if (mon > 12) mon = 1, yea ++;
					if (mon < 1) mon = 12, yea --;

					if (mon > _month && yea === _year) return;
					let mon1 = mon < 10 ? "0" + mon : mon;
					this.month = mon;
					this.year = yea;
					// let right = this.transDate(this.year, this.month, this.days[mon]);
					this.date = this.year + "-" + mon1 + "-01" + " ~ "+ this.year + "-" + mon1 + "-" + this.days[mon];
					this.__getPie({"year": this.year, "month": this.month});					
				}
			},
			async __getPie(_date = this.day) {
				// console.log('date: ', _date)
				const data = this.dateIndex <= 1 ? {
					cid: this.$store.getters.getUser.cid,
					day: _date,
					type: 1,
				} : {
					cid: this.$store.getters.getUser.cid,
					year: _date.year,
					month: _date.month,
					type: 1,
				}
				// console.log(data);
				this.pieData = [];
				let res;
				if (this.dateIndex == 0) res = await getPieDayApi(data);
				else if (this.dateIndex == 1) res = await getPieWeekApi(data);
				else if (this.dateIndex == 2) res = await getPieMonthApi(data);
				// this.pieData = res.data
				// console.log('pieData: ', res)
				if(res.status == this.API_STATUS_CODE.SUCCESS) {
					for (let item of res.data) {
						let good=this.getGood(item.gid)
						let obj={
							value: item.qty,
							name: good.name,
							per: item.per,
							unit: good.unit,
						}
						this.pieData.push(obj)
					}
					// console.log('pieData: ', this.pieData)
					this.ec.option.series[0].data=this.pieData
					// this.ec.option.color=this.ec.option.color
					this.sum=res.sum
				}else {
					uni.showToast({
						icon: 'error',
						title: '接口调用失败',
						duration: 3000
					})
					console.log('3')
				}	
			},
			getGood(gid) {
				let a={}
				for (let item of this.allGoods) {
					if(item.gid == gid) {
						let ss={
							name: item.shortName,
							unit: item.unit,
						}
						return ss
					}
				}
				return a
			},
			dateUnit(index) {				
				if (this.dateIndex != index){					
					this.dateIndex = index;
					if (index <= 1){
						let dateParam = this.currentTime(0);
						if (!index) this.date = dateParam;
						else {
							var monday = this.getMonday(new Date());
							var sunday = this.getSunday(new Date());
							this.date = monday + ' ~ ' + sunday;
						}
						this.__getPie(dateParam);
					} else if (index === 2){
						let dateParam = this.currentTime(2);
						this.__getPie(dateParam);
						
						let mon = dateParam.month;
						if (dateParam.month < 10) dateParam.month = '0' + dateParam.month;						
						var left = dateParam.year + '-' + dateParam.month + '-01';
						var right = dateParam.year + '-' + dateParam.month + '-' + this.days[mon];
						this.date = left + ' ~ ' + right;
					}
				}
			},
			transDate(year, month, day){
				return year+"-"+(month<10 ? "0"+month : month)+"-"+(day<10 ? "0"+day : day);
			}, 
			currentTime(val = -1) {
				var date = new Date();
				let year = date.getFullYear(); //月份从0~11，所以加一
				let month = date.getMonth()+1;
				let day = date.getDate();
				this.year = year;
				this.month = month;
				this.day = day;
				if (val <= 1) {
					return this.transDate(year, month, day);
				} else if (val === 2){
					return {"year": year, "month": month};
				}
				// console.log(year, month, day)
			},
			getMonday(date){
				var day=date.getDay();
				var deltaDay;
				if (day==0){
					deltaDay=6;
				} else{
					deltaDay=day-1;
				}
				var monday = new Date(date.getTime()-deltaDay*24*60*60*1000);
				// monday.setHours(0);
				// monday.setMinutes(0);
				// monday.setSeconds(0);
				// return monday;  //返回本周的周一的0时0分0秒
				
				let year = monday.getFullYear(); //月份从0~11，所以加一
				let month = monday.getMonth()+1;
				day = monday.getDate();
				return this.transDate(year, month, day);
			},
			getSunday(date){
				var day=date.getDay();
				var deltaDay = day ? 7 - day : 0;
				// console.log(day+'---',deltaDay)
				var sunday = new Date(date.getTime() + deltaDay*24*60*60*1000);
				// sunday.setHours(0);
				// sunday.setMinutes(0);
				// sunday.setSeconds(0);
				// return sunday;  //返回本周的周一的0时0分0秒
				
				let year = sunday.getFullYear(); //月份从0~11，所以加一
				let month = sunday.getMonth()+1;
				day = sunday.getDate();
				return this.transDate(year, month, day);
			}			
		}
	}
</script>

<style lang="less" scoped>
	.carbon-footprint {
		width: 100%;
		margin-top: 30rpx;
		padding: 30rpx;
		padding-top: 12rpx;
		box-sizing: border-box;
		border-radius: 25rpx;
		background-color: rgba(255,255,255,.1);
		
		.date {
			text-align: center;
			color: #fff;
			font-size: 35rpx;
		}
		
		.top {
			display: flex;
			align-items: center;
			justify-content: space-between;
			
			.title {
				color: #fff;
				margin-right: 10rpx;
				font-size: 35rpx;
				
				view {
					display: inline-block;
				}
			}
			
			.switch {
				display: flex;
				align-items: center;
				
				.fx {
					font-size: 70rpx;
					color: #fff;
				}
			}
		}
		
		.range {
			display: flex;
			align-items: center;
			justify-content: space-around;
			width: 60%;
			height: 60rpx;
			color: #dde0ed;
			margin: 20rpx auto;
			border: 1px solid #dde0ed;
			border-radius: 40rpx;
			box-sizing: border-box;
			
			.item {
				width: 33%;
				height: 100%;
				line-height: 55rpx;
				text-align: center;
				border-right: 1px solid #dde0ed;
			}
			
			:last-child {
				border-right: none;
			}
			
			.check {
				color: #fff;
				font-weight: 500;
			}
		}
		
		.content {
			width: 100%;
			text-align: center;
			// background-color: pink;
			
			image {
				width: 50%;
				
			}
			
			.echarts-content {
				text-align: center;
				
				.echarts {
					width: 100%;
					height: 450rpx;
					text-align: center;
				}
			}
			
			.list-content {
				display: flex;
				align-items: center;
				justify-content: space-between;
				flex-wrap: wrap;
				
				.item {
					width: 45%;
					// background-color: pink;
					
					.card-item {
						display: flex;
						position: relative;
						align-items: center;
						justify-content: space-between;
						box-sizing: border-box;
						padding: 20rpx 0rpx 0 30rpx;
						
						.circle {
							position: absolute;
							top: 52rpx;
							left: -6rpx;
							width: 15rpx;
							height: 15rpx;
							background-color: #fff;
							border-radius: 15rpx;
						}
						
						.name {
							color: #fff;
							font-size: 31rpx;
							text-align: left;
							
							view {
								font-size: 30rpx;
								color: #dde0ed;
								margin-top: 10rpx;
							}
						}
					
						.percent {
							color: #dde0ed;
							font-size: 30rpx;
						}
					}
				
				}
				
			}
			
		}
	}
</style>
